<template>
  <div class="node">
    <el-row>



      <!-- 头部2 -->
      <el-col :span="24">
        <div>
          <!-- 包一层卡片 -->
          <el-card class="node-head-card" shadow="never" :body-style=" {padding:'10px'}">
            <el-row>
              <!-- 创建按钮 -->
              <el-col :span="2">
                <div>
                  <!-- 点击后打开抽屉，填入创建node需要的数据 -->
                  <el-button
                      disabled
                      style="border-radius:2px;"
                      icon="Edit"
                      type="primary"
                      @click="createNodeDrawer = true"
                      v-loading.fullscreen.lock="fullscreenLoading">
                    创建
                  </el-button>
                </div>
              </el-col>
              <!-- 搜索框和搜索按钮 -->
              <el-col :span="6">
                <div>
                  <el-input class="node-head-search" clearable placeholder="请输入" v-model="searchInput"></el-input>
                  <el-button style="border-radius:2px;" icon="Search" type="primary" plain @click="getNodes()">搜索</el-button>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </div>
      </el-col>

      <!-- 数据表格 -->
      <el-col :span="24">
        <div>
          <!-- 包一层卡片 -->
          <el-card class="node-body-card" shadow="never" :body-style=" {padding:'5px'}">
            <!-- 数据表格 -->
            <!-- v-loading用于加载时的loading动画 -->
            <el-table
                style="width:100%;font-size:12px;margin-bottom:10px;"
                :data="nodeList"
                v-loading="appLoading"
                :row-key="getRowKeys"
                :expand-row-keys="expandKeys"
                @expand-change="expandChange">
              <!-- 最左侧留出20px的宽度，更加没关 -->
              <el-table-column width="20"></el-table-column>


              <el-table-column align=left label="Node名">
                <template v-slot="scope">
                  <p class="node-body-nodename">{{ scope.row.metadata.name }}</p>
                  <p class="node-body-ip">{{ scope.row.status.addresses[0].address }}</p>
                </template>
              </el-table-column>
              <el-table-column align=center label="规格">
                <template v-slot="scope">
                  <el-tag type="warning">{{ scope.row.status.capacity.cpu }}核{{
                      specTrans(scope.row.status.capacity.memory) }}G</el-tag>
                </template>
              </el-table-column>
              <el-table-column align=center label="POD-CIDR">
                <template v-slot="scope">
                  <span>{{ scope.row.spec.podCIDR }} </span>
                </template>
              </el-table-column>
              <el-table-column align=center label="版本">
                <template v-slot="scope">
                  <span>{{ scope.row.status.nodeInfo.kubeletVersion }} </span>
                </template>
              </el-table-column>
              <el-table-column align=center min-width="100" label="创建时间">
                <template v-slot="scope">
                  <el-tag type="info">{{ timeTrans(scope.row.metadata.creationTimestamp) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column align=center label="操作" width="200">
                <template v-slot="scope">
<!--                  <el-button size="small" style="border-radius:2px;" icon="Edit" type="primary" plain @click="getPodDetail(scope)">YAML</el-button>-->
                  <el-button size="small" style="border-radius:2px;" icon="Delete" type="warning" disabled>详情</el-button>
                </template>
              </el-table-column>

            </el-table>
            <!-- 分页配置 -->
            <!-- background 背景色灰 -->
            <!-- size-change 单页大小改变后触发 -->
            <!-- current-change 页数改变后触发 -->
            <!-- current-page 当前页 -->
            <!-- page-size 单页大小 -->
            <!-- layout 分页器支持的功能 -->
            <!-- total 数据总条数 -->
            <el-pagination
                class="node-body-pagination"
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="pagesizeList"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="nodeTotal">
            </el-pagination>
          </el-card>
        </div>
      </el-col>

    </el-row>



    <!--展示YAML信息的弹框-->
    <el-dialog title="YAML信息" v-model="yamlDialog" width="45%" top="2%">
      <!-- codemirror编辑器 -->
      <!-- border 带边框 -->
      <!-- options 编辑器配置 -->
      <!-- change 编辑器中的内容变化时触发 -->
      <codemirror
          :value="contentYaml"
          border
          :options="cmOptions"
          height="500"
          style="font-size:14px;"
          @change="onChange" >
      </codemirror>
      <template #footer>
      <span class="dialog-footer">
      	<el-button @click="yamlDialog = false">取 消</el-button>
      	<el-button type="primary" @click="updateNode()">更 新</el-button>
    	</span>
      </template>
    </el-dialog>



  </div>
</template>
<script>
import common from "../common/Config";
import httpClient from '../../utils/request';

import yaml2obj from 'js-yaml';
import json2yaml from 'json2yaml';//需要npm install json2yaml

//引入xterm终端依赖
import { Terminal } from 'xterm';
import { FitAddon } from 'xterm-addon-fit';
import 'xterm/css/xterm.css';
import 'xterm/lib/xterm.js';

export default {
  data() {
    return {
      //命名空间
      namespaceValue: 'default',
      namespaceList: [],
      namespaceListUrl: common.k8sNamespaceList,

      //头部工具二部分
      //搜索框内容
      searchInput: '',


      //分页
      currentPage: 1,
      pagesize: 10,
      pagesizeList: [10, 20, 30],
      //列表
      appLoading: false,
      nodeList: [],
      nodeTotal: 0,
      getNodesData: {
        url: common.k8sNodeList,
        params: {
          filter_name: '',
          namespace: '',
          page: 1,
          limit: 10,
        }
      },

      //编辑器配置
      cmOptions: common.cmOptions,
      contentYaml: '',
      //详情
      nodeDetail: {},
      getNodeDetailData: {
        url: common.k8sNodeDetail,
        params: {
          node_name: '',
          namespace: ''
        }
      },
      //yaml更新
      yamlDialog: false,
      updateNodeData: {
        url: common.k8sNodeUpdate,
        params: {
          namespace: '',
          content: ''
        }
      },


      //删除
      delNodeData: {
        url: common.k8sNodeDel,
        params: {
          node_name: '',
          namespace: '',
        }
      },

      //expand扩展
      //tab栏
      activeName: 'container',
      //展开和关闭
      expandKeys: [],
      //标记打开和关闭，用于node名
      expandMap: {},

      //日志
      //获取容器
      containerList: {},
      containerValue: '',
      getNodeContainerData: {
        url: common.k8sNodeContainer,
        params: {
          node_name: '',
          namespace: ''
        }
      },
      //获取日志
      logContent: '',
      getNodeLogData: {
        url: common.k8sNodeLog,
        params: {
          container_name: '',
          node_name: '',
          namespace: ''
        }
      },

      //terminal
      term: null,
      socket: null

    }
  },
  methods: {
    //获取Namespace列表
    getNamespaces() {
      httpClient.get(this.namespaceListUrl)
          .then(res => {
            this.namespaceList = res.data.items
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    //头部工具二部分
    //处理抽屉的关闭，增加体验感
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(() => {
            done();
          })
          .catch(() => {});
    },


    //页面大小发生变化时触发，赋值并重新获取列表
    handleSizeChange(size) {
      this.pagesize = size;
      this.getNodes()
    },
    //页数发生变化时触发，复制并重新获取列表
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getNodes()
    },
    //字符串截取、拼接并返回
    ellipsis(value) {
      return value.length>15?value.substring(0,15)+'...':value
    },
    //格林威治时间转为北京时间
    timeTrans(timestamp) {
      let date = new Date(new Date(timestamp).getTime() + 8 * 3600 * 1000)
      date = date.toJSON();
      date = date.substring(0, 19).replace('T', ' ')
      return date
    },
    //获取Node列表
    getNodes() {
      //表格加载动画开启
      this.appLoading = true
      //getNodesData是用于发起node列表请求的专用的对象，里面有url和params参 数,以下是赋值
      this.getNodesData.params.filter_name = this.searchInput
      this.getNodesData.params.namespace = this.namespaceValue
      this.getNodesData.params.page = this.currentPage
      this.getNodesData.params.limit = this.pagesize
      httpClient.get(this.getNodesData.url, {params: this.getNodesData.params})
          .then(res => {
            //响应成功，获取node列表和total
            this.nodeList = res.data.items
            this.nodeTotal = res.data.total
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
      //加载动画关闭
      this.appLoading = false
    },

    //json转yaml方法
    transYaml(content) {
      return json2yaml.stringify(content)
    },
    //yaml转对象
    transObj(content) {
      return yaml2obj.load(content)
    },
    //编辑器内容变化时触发的方式,用于将更新的内容复制到变量中
    onChange(val) {
      this.contentYaml = val
    },
    //获取node详情，e参数标识传入的scope插槽，.row是该行的数据
    getNodeDetail(e) {
      this.getNodeDetailData.params.node_name = e.row.metadata.name
      this.getNodeDetailData.params.namespace = this.namespaceValue
      httpClient.get(this.getNodeDetailData.url, {params: this.getNodeDetailData.params})
          .then(res => {
            //响应成功，获得node详情
            this.nodeDetail = res.data
            //将对象转成yaml格式的字符串
            this.contentYaml = this.transYaml(this.nodeDetail)
            //打开弹出框
            this.yamlDialog = true
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },
    //更新node
    updateNode() {
      //将yaml格式的node对象转为json
      let content = JSON.stringify(this.transObj(this.contentYaml))
      this.updateNodeData.params.namespace = this.namespaceValue
      this.updateNodeData.params.content = content
      httpClient.put(this.updateNodeData.url, this.updateNodeData.params)
          .then(res => {
            this.$message.success({
              message: res.msg
            })
            //更新后重新获取列表
            this.getNodes()
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
      //关闭弹出框
      this.yamlDialog = false
    },




    //弹出确认框，用于危险操作的double check
    //obj是行数据，opeateName是操作名，fn是操作的方法
    handleConfirm(obj, operateName, fn) {
      this.confirmContent = '确认继续 ' + operateName + ' 操作吗？'
      //$confirm用于弹出确认框
      this.$confirm(this.confirmContent,'提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
          .then(() => {
            //restartNode(e)或者delNode(e)
            fn(obj)
          })
          .catch(() => {
            this.$message.info({
              message: '已取消操作'
            })
          })
    },

    //删除node
    delNode(e) {
      this.delNodeData.params.node_name = e.row.metadata.name
      this.delNodeData.params.namespace = this.namespaceValue
      httpClient.delete(this.delNodeData.url, {data: this.delNodeData.params})
          .then(res => {
            this.$message.success({
              message: res.msg
            })
            this.getNodes()
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    //计算重启次数
    restartTotal(e) {
      let index, sum = 0
      let containerStatuses = e.row.status.containerStatuses
      for ( index in containerStatuses) {
        sum = sum + containerStatuses[index].restartCount
      }
      return sum
    },

    //展开和关闭
    getRowKeys(row) {
      return row.metadata.name
    },
    //row，展开的当前行的数据
    //expandedRows，展开的所有行的数据组成的数组，但是这里用法是只会有一行，也就是数组长度永远 为1
    expandChange(row, expandedRows) {
      //初始化变量
      //清空expandKeys，代表关闭所有展开的行
      this.expandKeys = []
      //清空日志内容
      this.logContent= ''
      //清空containervalue，展开时不显示上次的值
      this.containerValue = ''
      //将tab标签页顶部页面调成容器
      this.activeName = 'container'

      //expandedRows.length == 1表示展开，expandedRows.length == 0 表示关闭
      if (expandedRows.length > 0) {
        //expandMap key表示展开过的行的key，值为1表示展开标记，值为0表示关闭标记
        //expandMap用于数据表格点击name的展开，用于判断这一行是展开还是关闭的行为
        this.expandMap[row.metadata.name] = 1
        //将expandMap除了row.metadata.name，其他key的值都置为0
        this.setExpandMap(row.metadata.name)
        //这里才是真正的展开，将row.metadata.name添加到expandKeys数组中展开，然后执行方 法获取container
        this.expandKeys.push(row.metadata.name)
        this.getNodeContainer(row)
      } else {
        //关闭标记
        this.expandMap[row.metadata.name] = 0
      }

      // //判断是展开还是关闭
      // if (expandedRows.length > 0) {
      //   this.expandKeys.push(row.metadata.name)
      // }

    },
    //匹配expandMap中nodeName，不相等的全都置为0，意为除了nodeName这行，其他全都标记关闭
    setExpandMap(nodeName) {
      let key
      for ( key in this.expandMap ) {
        key !== nodeName ? this.expandMap[key] = 0 : ''
      }
    },

    getNodeContainer(row) {
      this.getNodeContainerData.params.node_name = row.metadata.name
      this.getNodeContainerData.params.namespace = this.namespaceValue
      httpClient.get(this.getNodeContainerData.url, {params:
        this.getNodeContainerData.params})
          .then(res => {
            this.containerList = res.data
            this.containerValue = this.containerList[0]
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },
    getNodeLog(nodeName) {
      this.getNodeLogData.params.node_name = nodeName
      this.getNodeLogData.params.container_name = this.containerValue
      this.getNodeLogData.params.namespace = this.namespaceValue
      httpClient.get(this.getNodeLogData.url, {params:
        this.getNodeLogData.params})
          .then(res => {
            this.logContent = res.data
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },


    //terminal
    initTerm() {
      //初始化xterm实例
      this.term = new Terminal({
        rendererType: 'canvas', //渲染类型
        rows: 30, //行数
        cols: 110,
        convertEol: false, //启用时，光标将设置为下一行的开头
        scrollback: 10, //终端中的回滚量
        disableStdin: false, //是否应禁用输入
        cursorStyle: 'underline', //光标样式
        cursorBlink: true, //光标闪烁
        theme: {
          foreground: 'white', //字体
          background: '#060101', //背景色
          cursor: 'help' //设置光标
        }
      });
      //绑定dom
      this.term.open(document.getElementById('xterm'))
      //终端适应父元素大小
      const fitAddon = new FitAddon()
      this.term.loadAddon(fitAddon)
      fitAddon.fit();
      //获取终端的焦点
      this.term.focus();
      let _this = this; //一定要重新定义一个this，不然this指向会出问题
      //onData方法用于定义输入的动作
      this.term.onData(function (key) {
        // 这里key值是输入的值，数据格式就是后端定义的
        //{"operation":"stdin","data":"ls"}
        let msgOrder = {
          operation: 'stdin',
          data: key,
        };
        //发送数据,string转json
        _this.socket.send(JSON.stringify(msgOrder));
      });
      //发送resize请求
      let msgOrder2 = {
        operation: 'resize',
        cols: this.term.cols,
        rows: this.term.rows,
      };
      this.socket.send(JSON.stringify(msgOrder2))
    },
    //初始化websocket
    initSocket(row) {
      //定义websocket连接地址
      let terminalWsUrl = common.k8sTerminalWs + "?node_name=" +
          row.metadata.name + "&container_name=" + this.containerValue + "&namespace=" +
          this.namespaceValue
      //实例化
      this.socket = new WebSocket(terminalWsUrl);
      //关闭连接时的方法
      this.socketOnClose();
      //建立连接时的方法
      this.socketOnOpen();
      //接收消息的方法
      this.socketOnMessage();
      //报错时的方法
      this.socketOnError();
    },
    socketOnOpen() {
      this.socket.onopen = () => {
        //简历连接成功后，初始化虚拟终端
        this.initTerm()
      }
    },
    socketOnMessage() {
      this.socket.onmessage = (msg) => {
        //接收到消息后将字符串转为对象，输出data内容
        let content = JSON.parse(msg.data)
        this.term.write(content.data)
      }
    },
    socketOnClose() {
      this.socket.onclose = () => {
        //关闭连接后打印在终端里
        this.term.write("链接已关闭")
      }
    },
    socketOnError() {
      this.socket.onerror = () => {
        console.log('socket 链接失败')
      }
    },
    //关闭连接
    closeSocket() {
      //若没有实例化，则不需要关闭
      if (this.socket === null) {
        return
      }
      this.term.write("链接关闭中。。。")
      this.socket.close()
    },

    //将内存的单位从Ki转为Gi
    specTrans(str){
      if(str.indexOf('Ki')==-1){
        return str
      }
      let num=str.slice(0,-2) / 1024 / 1024
      return num.toFixed(0)
    },

  },
  watch: {
    //监听namespace的值,若发生变化，则执行handler方法中的内容
    namespaceValue: {
      handler() {
        //将namespace的值存入本地，用于path切换时依旧能获取得到
        localStorage.setItem('namespace', this.namespaceValue)

        //重置当前页为1
        this.currentPage = 1
        //获取node列表
        this.getNodes()
      }
    },

    //若tab标签页切到日志，则重新加载日志内容
    activeName: {
      handler() {
        if ( this.activeName == 'log' ) {
          this.expandKeys.length == 1 ? this.getNodeLog(this.expandKeys[0]) :''
        }
      }
    }

  },
  beforeMount() {
    //加载页面时先获取localStorage中的namespace值，若获取不到则默认default
    if (localStorage.getItem('namespace') !== undefined && localStorage.getItem('namespace') !== null) {
      this.namespaceValue = localStorage.getItem('namespace')
    }
    this.getNamespaces()
    this.getNodes()

    //若websocket连接没有关闭，则在改生命周期关闭
    if ( this.socket !== null ) {
      this.socket.close()
    }

  },



}
</script>
<style scoped>
/* 卡片属性 */
.node-head-card,.node-body-card {
  border-radius: 1px;
  margin-bottom: 5px;
}

/*头部工具2部分*/
/* 卡片属性 */
.node-head-card,.node-body-card {
  border-radius: 1px;
  margin-bottom: 5px;
}
/* 搜索框 */
.node-head-search {
  width:160px;
  margin-right:10px;
}

/*数据表格*/
/* 数据表格node名颜色 */
.node-body-nodename {
  color: #4795EE;
}
/* node名鼠标悬停 */
.node-body-nodename:hover {
  color: rgb(84, 138, 238);
  cursor: pointer;
  font-weight: bold;
}

/* node状态栏圆点的css实现 */
.success-dot{
  display:inline-block;
  width: 7px;
  height:7px;
  background: rgb(27, 202, 21);
  border-radius:50%;
  border:1px solid rgb(27, 202, 21);
  margin-right: 10px;
}
.warning-dot{
  display:inline-block;
  width: 7px;
  height:7px;
  background: rgb(233, 200, 16);
  border-radius:50%;
  border:1px solid rgb(233, 200, 16);
  margin-right: 10px;
}
.error-dot{
  display:inline-block;
  width: 7px;
  height:7px;
  background: rgb(226, 23, 23);
  border-radius:50%;
  border:1px solid rgb(226, 23, 23);
  margin-right: 10px;
}
.success-status {
  color: rgb(27, 202, 21);
}
.warning-status {
  color: rgb(233, 200, 16);
}
.error-status {
  color: rgb(226, 23, 23);
}

/deep/ .el-tabs__item {
  font-size: 12px;
}
/deep/ .el-tabs__header {
  margin-bottom: 8px;
}

/*容器日志*/
.node-body-log-card, .node-body-shell-card {
  border-radius:1px;
  height:600px;
  overflow:auto;
  background-color: #060101;
}
.node-body-log-card {
  color: aliceblue;
}
.node-body-log-span {
  white-space:pre;
}
</style>